package com.xindaoapp.happypet.viewpager.windows;

import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.text.Html;
import android.text.SpannableStringBuilder;
import android.util.Pair;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.HeaderViewListAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.activity.PrivateLetterActivity;
import com.xindaoapp.happypet.adapter.XinDaoBaseAdapter;
import com.xindaoapp.happypet.application.HappyPetApplication;
import com.xindaoapp.happypet.bean.InformMessage;
import com.xindaoapp.happypet.bean.MessageInfo;
import com.xindaoapp.happypet.bean.ReplyInfo;
import com.xindaoapp.happypet.ui.PostDetailActivity;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.IRequest;
import com.xindaoapp.happypet.utils.TimeFormat;
import com.xindaoapp.happypet.viewpager.ViewPagerWindow;

/**
 * 消息中心->我的消息
 * 
 * @author chenghao
 */
public class ReplyWindow extends ViewPagerWindow {
    public static enum MessageTabType {
        REPLY, INFORM, LETTER
    }

    private PullToRefreshListView listView;


    private final MessageTabType type;

    private boolean isSetResult;

    public ReplyWindow(Activity context, MessageTabType type) {
        super(context);
        this.type = type;
    }

    public ReplyWindow(Activity context, MessageTabType type, boolean isSetResult) {
        super(context);
        this.type = type;
        this.isSetResult = isSetResult;
    }

    @Override
    public View onCreateView() {
        return View.inflate(getBaseContext(), R.layout.message_center_reply, null);
    }

    @Override
    protected void onLoadDatas() {
        if (type == MessageTabType.REPLY) {
            loadReply();
        } else if (type == MessageTabType.INFORM) {
            loadInform();
        } else if (type == MessageTabType.LETTER) {
            loadLetter();
        }
    }

    /** 私信 */
    private void loadLetter() {
        HappyPetApplication
                .get()
                .getMoccaApi()
                .getPrivateMessageList(Constants.PAGE_FIRST, Constants.PAGE_SIZE,
                        new IRequest<List<MessageInfo>>() {

                            @Override
                            public void request(List<MessageInfo> t) {
                                if (null != t) {
                                    if (null == listView.getRefreshableView().getAdapter()) {
                                        listView.setAdapter(new PrivateMessageAdapter(
                                                getBaseContext(), t, Constants.PAGE_SIZE,
                                                R.layout.message_center_item_reply,
                                                R.layout.item_loading));
                                    } else {
                                        PrivateMessageAdapter adapter =
                                                (PrivateMessageAdapter) ((HeaderViewListAdapter) listView
                                                        .getRefreshableView().getAdapter())
                                                        .getWrappedAdapter();
                                        adapter.setInitData(t);
                                        adapter.notifyDataSetChanged();
                                    }
                                    onDataArrived(true);

                                    if (t.size() == 0) {
                                        onNoDataArrived();
                                    }
                                } else {
                                    onDataArrived(false);
                                    onNoDataArrived();
                                }
                                listView.onRefreshComplete();
                            }
                        });
    }

    private void loadInform() {
        HappyPetApplication
                .get()
                .getMoccaApi()
                .getInformMessageList(UserState.getUserUid(), Constants.PAGE_FIRST,
                        Constants.PAGE_SIZE, new IRequest<List<InformMessage>>() {

                            @Override
                            public void request(List<InformMessage> t) {
                                if (null != t) {
                                    if (null == listView.getRefreshableView().getAdapter()) {
                                        listView.setAdapter(new InformMessageAdapter(
                                                getBaseContext(), t, Constants.PAGE_SIZE,
                                                R.layout.message_center_item_reply,
                                                R.layout.item_loading));
                                    } else {
                                        InformMessageAdapter adapter =
                                                (InformMessageAdapter) ((HeaderViewListAdapter) listView
                                                        .getRefreshableView().getAdapter())
                                                        .getWrappedAdapter();
                                        adapter.setInitData(t);
                                        adapter.notifyDataSetChanged();
                                    }
                                    onDataArrived(true);

                                    if (t.size() == 0) {
                                        onNoDataArrived();
                                    }

                                } else {
                                    onDataArrived(false);
                                }
                                listView.onRefreshComplete();
                            }
                        });
    }

    private void loadReply() {
        HappyPetApplication
                .get()
                .getMoccaApi()
                .getReplyList(UserState.getUserUid(), Constants.PAGE_FIRST, Constants.PAGE_SIZE,
                        new IRequest<List<ReplyInfo>>() {

                            @Override
                            public void request(List<ReplyInfo> t) {
                                if (null != t) {
                                    if (null == listView.getRefreshableView().getAdapter()) {
                                        listView.setAdapter(new ReplyAdapter(getBaseContext(), t,
                                                Constants.PAGE_SIZE,
                                                R.layout.message_center_item_reply,
                                                R.layout.item_loading));
                                    } else {
                                        ReplyAdapter adapter =
                                                (ReplyAdapter) ((HeaderViewListAdapter) listView
                                                        .getRefreshableView().getAdapter())
                                                        .getWrappedAdapter();
                                        adapter.setInitData(t);
                                        adapter.notifyDataSetChanged();
                                    }
                                    onDataArrived(true);

                                    if (t.size() == 0) {
                                        onNoDataArrived();
                                    }

                                } else {
                                    onDataArrived(false);
                                }
                                listView.onRefreshComplete();
                            }
                        });
    }

    @Override
    protected void initViews() {
        super.initViews();
        listView = (PullToRefreshListView) getView().findViewById(R.id.listview);
        listView.setMode(Mode.PULL_FROM_START);
        listView.setOnRefreshListener(new OnRefreshListener<ListView>() {

            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                onLoadDatas();
            }
        });
        listView.getRefreshableView().setOnItemLongClickListener(new OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(final AdapterView<?> parent, View view,
                    final int position, long id) {
                new AlertDialog.Builder(getBaseContext()).setTitle("消息").setMessage("确认删除？")
                        .setNegativeButton("取消", null)
                        .setPositiveButton("确定", new OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                String noticeId = "";
                                if (type == MessageTabType.REPLY) {
                                    noticeId =
                                            ((ReplyInfo) parent.getAdapter().getItem(position)).id;
                                } else if (type == MessageTabType.INFORM) {
                                    noticeId =
                                            ((InformMessage) parent.getAdapter().getItem(position)).id;
                                }
                                delete(noticeId);
                            }
                        }).create().show();
                return false;
            }
        });

    }

    private void delete(String noticeId) {
        HappyPetApplication.get().getMoccaApi()
                .deleteInformMessage(noticeId, new IRequest<Pair<Boolean, String>>() {

                    @Override
                    public void request(Pair<Boolean, String> t) {
                        if (null != t) {
                            if (t.first) {
                                onLoadDatas();
                            }
                            Toast.makeText(getBaseContext(), t.second, Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(getBaseContext(), R.string.net_error, Toast.LENGTH_SHORT)
                                    .show();
                        }
                    }
                });
    }

    private void deletePrivate(String touid) {
        HappyPetApplication.get().getMoccaApi()
                .deletePrivateMessageWithUid(touid, new IRequest<Pair<Boolean, String>>() {

                    @Override
                    public void request(Pair<Boolean, String> t) {
                        if (null != t) {
                            if (t.first) {
                                onLoadDatas();
                            }
                            Toast.makeText(getBaseContext(), t.second, Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(getBaseContext(), R.string.net_error, Toast.LENGTH_SHORT)
                                    .show();
                        }
                    }
                });
    }

    /**
     * 回复
     * 
     * @author xindaoapp
     */
    class ReplyAdapter extends XinDaoBaseAdapter<ReplyInfo> {

        private final int currentClickedPosition = -1;

        public ReplyAdapter(Context context, List<ReplyInfo> iniData, int pageSize, int res,
                int loadingRes) {
            super(context, iniData, pageSize, res, loadingRes);
        }

        @Override
        public void nextPage(int start, int size,
                final ILoadNextPageData<ReplyInfo> iLoadNextPageData) {
            HappyPetApplication
                    .get()
                    .getMoccaApi()
                    .getReplyList(UserState.getUserUid(), start, size,
                            new IRequest<List<ReplyInfo>>() {

                                @Override
                                public void request(List<ReplyInfo> t) {
                                    iLoadNextPageData.loadNextPageData(t);
                                }
                            });
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent,
                final ReplyInfo value) {
            ViewHolder holder = (ViewHolder) convertView.getTag();
            if (holder == null) {
                holder = new ViewHolder();
                holder.icon = (ImageView) convertView.findViewById(R.id.icon);
                holder.name = (TextView) convertView.findViewById(R.id.name);
                holder.time = (TextView) convertView.findViewById(R.id.time);
                holder.content = (TextView) convertView.findViewById(R.id.content);
                holder.replyContent = (TextView) convertView.findViewById(R.id.reply_content);
                holder.my = convertView.findViewById(R.id.my);
                convertView.setTag(holder);
            }
            ImageLoader.getInstance().displayImage(value.userface, holder.icon);
            holder.name.setText(value.author);

            holder.time.setText(TimeFormat.format(CommonUtil
                    .formatTime2Date(value.dateline * 1000l)));
            // holder.content.setText(Html.fromHtml(value.subject));

            SpannableStringBuilder ss = (SpannableStringBuilder) Html.fromHtml(value.subject);
            SpannableStringBuilder temp = ss;
            if (currentClickedPosition != position && ss.length() > 20) {
                temp = (SpannableStringBuilder) ss.subSequence(0, 20);

                SpannableStringBuilder ssb =
                        CommonUtil.convetToHtml(CommonUtil.parseEmoji(temp.toString()), mContext);

                holder.content.setText(ssb + "...");
            } else {
                SpannableStringBuilder ssb =
                        CommonUtil.convetToHtml(CommonUtil.parseEmoji(temp.toString()), mContext);
                holder.content.setText(ssb.toString());
            }
            SpannableStringBuilder ssb =
                    CommonUtil.convetToHtml(
                            CommonUtil.parseEmoji(Html.fromHtml(value.message).toString()),
                            mContext);
            // String.format("我：“%s”",
            holder.my.setVisibility(View.VISIBLE);
            holder.replyContent.setText(ssb);

            convertView.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // if (currentClickedPosition == position) {
                    // currentClickedPosition = -1;
                    // } else {
                    // currentClickedPosition = position;
                    // }
                    // notifyDataSetChanged();
                    if (isSetResult) {
                        Intent data = new Intent();
                        data.putExtra(Constants.KEY_POST_NAME, value.subject);
                        data.putExtra(Constants.KEY_POST_TID, value.tid);
                        ReplyWindow.this.mContext.setResult(Activity.RESULT_OK, data);
                        ReplyWindow.this.mContext.finish();
                    } else {
                        Intent intent = new Intent(mContext, PostDetailActivity.class);
                        intent.putExtra(Constants.KEY_POST_TID, value.tid);
                        intent.putExtra("pageNum", Integer.valueOf(value.curpage));
                        intent.putExtra("floor", Integer.valueOf(value.curposition));
                        mContext.startActivity(intent);
                    }
                }
            });
            convertView.setOnLongClickListener(new DeleteMessage(value.id));
            return convertView;
        }

        class ViewHolder {
            ImageView icon;
            TextView name;
            TextView time;
            TextView content;
            View my;
            TextView replyContent;
        }
    }

    /**
     * 通知
     * 
     * @author xindaoapp
     */
    class InformMessageAdapter extends XinDaoBaseAdapter<InformMessage> {

        private int currentClickedPosition = -1;

        public InformMessageAdapter(Context context, List<InformMessage> iniData, int pageSize,
                int res, int loadingRes) {
            super(context, iniData, pageSize, res, loadingRes);
        }

        @Override
        public void nextPage(int start, int size,
                final ILoadNextPageData<InformMessage> iLoadNextPageData) {
            HappyPetApplication
                    .get()
                    .getMoccaApi()
                    .getInformMessageList(UserState.getUserUid(), start, size,
                            new IRequest<List<InformMessage>>() {

                                @Override
                                public void request(List<InformMessage> t) {
                                    iLoadNextPageData.loadNextPageData(t);
                                }
                            });
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent,
                InformMessage value) {
            ViewHolder holder = (ViewHolder) convertView.getTag();
            if (holder == null) {
                holder = new ViewHolder();
                holder.icon = (ImageView) convertView.findViewById(R.id.icon);
                holder.name = (TextView) convertView.findViewById(R.id.name);
                holder.time = (TextView) convertView.findViewById(R.id.time);
                holder.content = (TextView) convertView.findViewById(R.id.content);
                holder.replyContent = (TextView) convertView.findViewById(R.id.reply_content);
                convertView.setTag(holder);
            }
            ImageLoader.getInstance().displayImage(value.userface, holder.icon);
            holder.name.setText("系统通知");

            holder.time.setText(TimeFormat.format(CommonUtil
                    .formatTime2Date(value.dateline * 1000l).toString()));

            SpannableStringBuilder ss = (SpannableStringBuilder) Html.fromHtml(value.note);
            SpannableStringBuilder temp = ss;
            if (currentClickedPosition != position && ss.length() > 20) {
                temp = (SpannableStringBuilder) ss.subSequence(0, 20);
                holder.content.setText(temp + "...");
            } else {
                holder.content.setText(temp);
            }

            convertView.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (currentClickedPosition == position) {
                        currentClickedPosition = -1;
                    } else {
                        currentClickedPosition = position;
                    }
                    notifyDataSetChanged();
                }
            });
            convertView.setOnLongClickListener(new DeleteMessage(value.id));
            return convertView;
        }

        class ViewHolder {
            ImageView icon;
            TextView name;
            TextView time;
            TextView content;
            TextView replyContent;
        }
    }

    class DeleteMessage implements OnLongClickListener {
        private final String noticeId;

        public DeleteMessage(String noticeId) {
            super();
            this.noticeId = noticeId;
        }

        @Override
        public boolean onLongClick(View arg0) {
            new AlertDialog.Builder(getBaseContext()).setTitle("消息").setMessage("确认删除？")
                    .setNegativeButton("取消", null).setPositiveButton("确定", new OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                            delete(noticeId);
                        }
                    }).create().show();
            return true;
        }

    }

    class DeletePrivateMessage implements OnLongClickListener {
        private final String touid;

        public DeletePrivateMessage(String touid) {
            super();
            this.touid = touid;
        }

        @Override
        public boolean onLongClick(View arg0) {
            new AlertDialog.Builder(getBaseContext()).setTitle("消息").setMessage("确认删除？")
                    .setNegativeButton("取消", null).setPositiveButton("确定", new OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                            deletePrivate(touid);
                        }
                    }).create().show();
            return true;
        }

    }

    /**
     * 私信
     * 
     * @author xindaoapp
     */
    class PrivateMessageAdapter extends XinDaoBaseAdapter<MessageInfo> {
        // private int currentClickedPosition = -1;
        public PrivateMessageAdapter(Context context, List<MessageInfo> iniData, int pageSize,
                int res, int loadingRes) {
            super(context, iniData, pageSize, res, loadingRes);
        }

        @Override
        public void nextPage(
                int start,
                int size,
                final com.xindaoapp.happypet.adapter.XinDaoBaseAdapter.ILoadNextPageData<MessageInfo> iLoadNextPageData) {
            HappyPetApplication.get().getMoccaApi()
                    .getPrivateMessageList(start, size, new IRequest<List<MessageInfo>>() {

                        @Override
                        public void request(List<MessageInfo> t) {
                            iLoadNextPageData.loadNextPageData(t);
                        }
                    });
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent,
                final MessageInfo value) {
            ViewHolder holder = (ViewHolder) convertView.getTag();
            if (holder == null) {
                holder = new ViewHolder();
                holder.icon = (ImageView) convertView.findViewById(R.id.icon);
                holder.name = (TextView) convertView.findViewById(R.id.name);
                holder.time = (TextView) convertView.findViewById(R.id.time);
                holder.content = (TextView) convertView.findViewById(R.id.content);
                holder.replyContent = (TextView) convertView.findViewById(R.id.reply_content);
                convertView.setTag(holder);
            }
            ImageLoader.getInstance().displayImage(value.userface, holder.icon);
            // 别人对自己发
            if (null != value.lastauthorid && !value.lastauthorid.equals(UserState.getUserUid())) {
                holder.name.setText(String.format("%s 对 您说", value.tousername));
            } else {// 自己对别人发
                holder.name.setText(String.format("您 对 %s说", value.tousername));
            }
            // TimeFormat.format(String.valueOf(value.dateline * 1000l))

            holder.time.setText(TimeFormat.format(value.addtime));

            SpannableStringBuilder ss = (SpannableStringBuilder) Html.fromHtml(value.lastsummary);

            SpannableStringBuilder ssb =
                    CommonUtil.convetToHtml(CommonUtil.parseEmoji(ss.toString()), mContext);

            holder.content.setText(ssb);

            convertView.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, PrivateLetterActivity.class);
                    intent.putExtra(Constants.KEY_USERNAME, value.tousername);
                    intent.putExtra(Constants.KEY_TOUID, value.msgtoid);
                    mContext.startActivity(intent);
                }
            });
            convertView.setOnLongClickListener(new DeletePrivateMessage(value.touid));
            return convertView;
        }

        class ViewHolder {
            ImageView icon;
            TextView name;
            TextView time;
            TextView content;
            TextView replyContent;
        }

    }

}
